/*
 * MIT License
 *
 * Copyright (c) 2020 wen.gu <454727014@qq.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

 /***************************************************************************
 * Name: kfa_writer.cpp
 *
 * Purpose: implementation a writer to write data to kfa file
 *
 * Developer:
 *   wen.gu , 2022-03-06
 *
 * TODO:
 *
 ***************************************************************************/

 /******************************************************************************
 **    INCLUDES
 ******************************************************************************/

#include "kfa_writer.h"

#include <stdio.h>
#include <string.h>

#include "kfa_encoder.h"

/******************************************************************************
 **    MACROS
 ******************************************************************************/
#define LOGE printf
#define LOGD printf
/******************************************************************************
 **    VARIABLE DEFINITIONS
 ******************************************************************************/

/******************************************************************************
 **    inner FUNCTION DEFINITIONS
 ******************************************************************************/
static uint32_t get_image_size(uint16_t img_width, uint16_t img_height, kfa_raw_type raw_type)
{
    switch (raw_type)
    {
    case kfa_raw_type::RGBA32: return img_width * img_height * 4; break;
    case kfa_raw_type::RGB24:  return img_width * img_height * 4; break;
    case kfa_raw_type::YUV420:
    case kfa_raw_type::NV12:
        return img_width * img_height * 3 / 2;
    break;
    default:
        break;
    }

    return 0;
}
/******************************************************************************
 **    FUNCTION DEFINITIONS
 ******************************************************************************/
KfaWrtier::KfaWrtier()
{
    //todo something
}

KfaWrtier::~KfaWrtier()
{
    //todo something
}

bool KfaWrtier::setOutputFile(const std::string& file_name)
{
    return muxer_.setOutputFile(file_name);
}

bool KfaWrtier::initialize(const KfaWriterInitializeParam& param, bool is_simulation)
{
    if (!is_initialized_)
    {
        if (!is_simulation)
        {
            if (!setOutputFile(param.file_name))
            {
                LOGE("open output file(%s) failed\n", param.file_name.c_str());
                return false;
            }            
        }


        const kfa_header& header = param.header;
        uint32_t src_img_size = get_image_size(header.width, header.height, header.raw_type);
        
        LOGD("kfa header(size: %d): fcc: 0x%08x, width: %d, height: %d, raw_type: %d, codec format: %d, version: %d\n", 
            sizeof(header), header.fourcc, header.width, header.height, (int32_t)header.raw_type, header.codec_format, header.version);     
        if (!is_simulation)
        {            
            if (muxer_.setHeader(header) == false)
            {
                LOGE("muxer set(write) header failed\n");
                return false;
            }  
        }

        encoder_ = KfaEncoder::create(param.header.codec_format);

        if (!encoder_)
        {
            LOGE("unsupported encoder type: %d\n", param.header.codec_format);
            return false;
        }

        is_initialized_ = true;                   
    }

    return true;
}

bool KfaWrtier::write(const uint8_t* data, uint32_t size, bool is_simulation, uint32_t file_size /** = 0*/)
{
    if (is_err_occur_)
    {
        return false;
    }

#if 1
    KfaBuffer out_buf;
    total_file_size_ += file_size;
    if (encoder_->encode(data, size, out_buf) == false)
    {
        LOGE("encode: failed\n");
        is_err_occur_ = true;
        return false;
    }
#if 0
    src_buf = encoder2_.get_src_buffer(src_size);
    difference_coding(data, src_buf, size);
    uint32_t dst_size2 = dst_size_;
    if (encoder2_.encode(src_buf, src_size, dst_buf_, dst_size2) == false)
    {
        LOGE("encode2: failed\n");
        is_err_occur_ = true;
        return false;
    }

    LOGE("encode pkt idx: %d,file size: %d, before size: %d, after size: %d,total: %d, after size2: %d, total2: %d\n",
        buf_idx_++, file_size, src_size, dst_size, total_out_size_, dst_size2, total_out_size2_);
#else
#if 0
    dst_size2 = dst_size_;
    if (encoder2_.encode(src_buf + src_size, size - src_size, dst_buf_, dst_size2) == false)
    {
        LOGE("encode2: failed\n");
        is_err_occur_ = true;
        return false;
    }
#endif    
    LOGE("encode pkt idx: %d,file size: %d,  before size: %d, after size: %d, total size: (file: %d, out:%d)\n", 
        buf_idx_++, file_size, size, out_buf.size, total_file_size_, total_out_size_);
#endif
    if (!is_simulation)
    {
        if (muxer_.write(out_buf.buf, out_buf.size) == false)
        {
            LOGE("mux : failed\n");
            is_err_occur_ = true;
            out_buf.release(out_buf);

            return false;            
        }        
    }

    total_out_size_ += out_buf.size;
    out_buf.release(out_buf);
    return true;
#else

    if (!fill_buffer_)
    {
        fill_buffer_ = encoder_.get_src_buffer(fill_buffer_size_);
    }

    total_file_size_ += file_size;
    if (fill_size_ < fill_buffer_size_)
    {
        memcpy(fill_buffer_ + fill_size_, data, size);
        fill_size_ += size;
        fill_count_++;
    }

    if (fill_size_ < fill_buffer_size_)
    {
        return true;
    }

    return doWrite(fill_buffer_, fill_size_, is_simulation);
#endif
    //return true;
}

#if 0
bool KfaWrtier::sync(bool is_simulation) /** write cached data in writer to file */
{
    if ((fill_size_ > 0) && (fill_count_ > 0))
    {
        uint32_t src_size = 0;
        uint8_t* src_buf = encoder_.get_src_buffer(src_size);

        return doWrite(src_buf, fill_size_, is_simulation);
    }

    return true;
}

bool KfaWrtier::doWrite(const uint8_t* data, uint32_t size, bool is_simulation)
{
    uint8_t* dst_buf = nullptr;
    uint32_t out_data_size = 0;

    if (encoder_.encode(data, size, dst_buf, out_data_size) == false)
    {
        LOGE("encode: failed, fill_size: %d, src_size: %d\n", fill_size_, size);
        is_err_occur_ = true;
        return false;
    }

    if (!is_simulation)
    {
        kfa_packet in_pkt;
        //in_pkt.frame_count = fill_count_;
        in_pkt.raw_size = size;
        in_pkt.size = out_data_size;
        in_pkt.data = dst_buf;
        if (muxer_.write(in_pkt) == false)
        {
            LOGE("mux : failed(cur block: frame count: %d, data size: %d)\n", fill_count_, out_data_size);
            is_err_occur_ = true;
            return false;            
        }        
    }

    total_out_size_ += out_data_size;
    
    LOGE("encode pkt idx: %d, frame count: %d, before size: %d, after size: %d, total size: (file: %d, out:%d)\n", 
        buf_idx_++, fill_count_, size, out_data_size, total_file_size_, total_out_size_);
    fill_size_ = 0;
    fill_count_ = 0;    
    fill_buffer_ = nullptr;

    return true;
}
#endif